<template>
  <div class="padding flex direction-column height-100">
    <div class="search-form">
      <el-form inline>
        <el-form-item v-if="isAdmin" label="企业名称">
          <el-select v-model="tenantId" filterable clearable placeholder="请选择">
            <el-option v-for="enterprise in enterpriseList" :key="enterprise.id" :label="enterprise.name" :value="enterprise.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="false" label="测点代码">
          <el-select v-model="tagCode" filterable clearable placeholder="请选择">
            <el-option v-for="option in options" :key="option.value" :label="option.label" :value="option.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="测点名称">
          <el-input v-model.trim="tagName" clearable placeholder="模糊查询测点"></el-input>
        </el-form-item>
        <el-form-item label="周期">
          <dictionary-picker dic-code="ZHOU_QI_LEI_XING" v-model="period" :clearable="false" @change="changePeriod"></dictionary-picker>
        </el-form-item>
        <el-form-item label="时间区间">
          <el-date-picker
            v-model="range" :clearable="false" :type="period === '2' ? 'daterange' : 'monthrange'"
            :format="period === '2' ? 'yyyy-MM-dd' : 'yyyy-MM'"
            :value-format="period === '2' ? 'yyyy-MM-dd' : 'yyyy-MM'"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="clickSearch">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div v-if="false" class="margin-bottom tabs-component">
      <custom-tabs :tabs="tabs" v-model="currentTabValue"></custom-tabs>
    </div>
    <template v-if="currentTabValue === 'CHART'">
      <div class="bg-white chart-content" style="height: 100%;" v-loading="loading" ref="container">
        <v-chart
          :option="chartOption" style="width:100%;height:100%;"
          :theme="chartTheme" autoresize
        ></v-chart>
      </div>
    </template>
    <template v-else>
      <div class="flex-1 overflow-auto dark-table-wrapper">
        <el-table
          v-loading="loading"  :data="lists" height="100%"
          :header-cell-style="{
            color: 'white',
            backgroundColor: themeColor
          }"
        >
          <div slot="empty" class="empty-lists">
            <i class="i-custom:search"></i>
            <span class="empty-text">暂无数据</span>
          </div>
          <el-table-column v-for="column in columns" :key="column.prop" v-bind="column">
            <template v-if="column.prop === 'val' && false" #default="{ row }">
              <input-number-editor
                v-if="row._editing" :value="row.value"
                @update="update(row, $event)"
              ></input-number-editor>
              <div v-else @click="row._editing = true" title="点击可修改">
                {{row.xval || row.val}}
                <i class="el-icon-edit" style="color: lightgray;"></i>
                <span style="margin-left:10px;color:var(--danger-color);" v-if="String(row.source) === '1'">(原数据：{{row.val}})</span>
              </div>
            </template>
            <template v-else-if="column.prop === 'source'" #default="{ row }">
              <span :style="{color: String(row.source) === '1' ? 'var(--danger-color)' : 'inherit'}">
                {{String(row.source) === '1' ? '手动' : '自动'}}
              </span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        class="pagination"
        layout="total, prev, pager, next" hide-on-single-page background
        :current-page.sync="pagination.pageNumber" :page-size="pagination.pageSize" :total="pagination.total"
        @current-change="query" @size-change="sizeChange"
      >
      </el-pagination>
    </template>
  </div>
</template>

<script>
import DictionaryPicker from '@/components/dictionary-picker'
import { realTimeDataPageList, realTimeDataList, updateRealTimeData } from '@/api/tagValueFifteen'
import { selectTagCodeList } from '@/api/indicator'
import CustomTabs from '@/components/custom-tabs'
import InputNumberEditor from '@/components/input-number-editor'
import MixinVchartTheme from '@/mixins/mixin-vchart-theme'

const api = {
  realTimeDataList,
  realTimeDataPageList,
  updateRealTimeData,
  selectTagCodeList,
}
export default {
  name: 'update-real-time-data',
  mixins: [MixinVchartTheme],
  components: { CustomTabs, DictionaryPicker, InputNumberEditor },
  props: {
    // 是否为政府端
    isAdmin: Boolean
  },
  data () {
    const today = this.$dayjs().format('YYYY-MM-DD')
    const before = this.$dayjs().subtract(7, 'day').format('YYYY-MM-DD')
    return {
      tagName: '',
      tagCode: '',
      options: [],
      range: [before, today],
      period: '2',
      loading: false,
      lists: [],
      allLists: [],
      columns: [
        // { label: 'ID', prop: 'id' },
        { label: '测点名称', prop: 'tagName' },
        { label: '测点代码', prop: 'tagCode' },
        { label: '所属企业', prop: 'enterpriseName' },
        { label: '数据时间', prop: 'dataTime' },
        { label: '数据值', prop: 'val' },
        { label: '周期', prop: 'cycle' },
        { label: '数据来源', prop: 'source' },
      ],
      pagination: {
        pageNumber: 1,
        pageSize: 20,
        total: 0,
      },
      tabs: [
        { name: '数据', value: 'DATA' },
        { name: '图表', value: 'CHART' },
      ],
      currentTabValue: 'DATA',
      tagUnit: '吨标准煤',

      tenantId: this.$route.query.enterpriseId ? Number(this.$route.query.enterpriseId) : '',
    }
  },
  computed: {
    themeColor () {
      return this.$store.state.user.theme
    },
    enterpriseList () {
      return this.$store.state.energyEnterpriseList
    },
    chartOption () {
      const { themeColor, tagUnit } = this
      const lists = this.allLists
      return {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
          },
        },
        grid: {
          left: '5%',
          right: '5%',
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: lists.map(v => v.dataTime),
        },
        yAxis: {
          type: 'value',
          name: tagUnit,
          axisLine: {
            show: true,
          },
        },
        series: [
          {
            name: '实时数据',
            type: 'line',
            smooth: true,
            itemStyle: {
              color: themeColor,
            },
            data: lists.map(v => Number(v.val))
          }
        ],
      }
    }
  },
  watch: {
    currentTabValue (val) {
      if (val === 'CHART') {
        this.allQuery()
      }
    },
    '$route.query.enterpriseId': function () {
      this.tenantId = Number(this.$route.query.enterpriseId)
    },
    tenantId () {
      // this.getOptions()
    },
  },
  mounted () {
    if (this.isAdmin) {
      this.$store.dispatch('GET_ENTERPRISE_LIST')
    }
    this.loading = true
    this.getOptions().then(() => {
      this.reload()
    })
  },
  methods: {
    changePeriod () {
      this.range = this.period === '2'
        ? [this.$dayjs().subtract(7, 'day').format('YYYY-MM-DD'), this.$dayjs().format('YYYY-MM-DD')]
        : [this.$dayjs().subtract(3, 'month').format('YYYY-MM'), this.$dayjs().format('YYYY-MM')]
    },
    getOptions () {
      const params = {
        tenantId: this.tenantId || ''
      }
      return api.selectTagCodeList(params).then(res => {
        if (res.code === 200) {
          this.options = res.data.map(v => ({
            label: v,
            value: v,
          }))
          this.tagCode = this.options[0] ? this.options[0].value : ''
        }
      })
    },
    reload () {
      this.clickSearch()
    },
    clickSearch () {
      const { currentTabValue } = this
      if (currentTabValue === 'DATA') {
        this.pagination.pageNumber = 1
        this.$nextTick(() => {
          this.query()
        })
      } else if (currentTabValue === 'CHART') {
        this.$nextTick(() => {
          this.allQuery()
        })
      }
    },
    sizeChange (pageSize) {
      this.pagination.pageSize = pageSize
      this.$nextTick(() => {
        this.reload()
      })
    },
    allQuery () {
      this.loading = true
      const [startTime, endTime] = this.range
      const params = {
        startTime,
        endTime,
        tagCode: this.tagCode.trim(),
        cycle: this.period,
        enterpriseId: this.tenantId || '',
      }
      return api.realTimeDataList(params).then(res => {
        if (res.code === 200) {
          this.allLists = res.data || []
        }
      }).finally(() => {
        this.loading = false
      })
    },
    query () {
      this.loading = true

      const [startTime, endTime] = this.range
      const params = {
        startTime,
        endTime,
        tagCode: this.tagCode.trim(),
        pageNumber: this.pagination.pageNumber,
        pageSize: this.pagination.pageSize,
        cycle: this.period,
        tagName: this.tagName,
        enterpriseId: this.tenantId || '',
      }
      return api.realTimeDataPageList(params).then(res => {
        if (res.code === 200) {
          res.data = res.data || {}
          res.data.records = res.data.records || []
          res.data.records.forEach(v => {
            v._editing = false
            v.value = v._value = v.xval || v.val
          })
          this.lists = res.data.records
          this.pagination.total = res.data.total || 0
        }
      }).finally(() => {
        this.loading = false
      })
    },
    update (row, { value, input }) {
      // eslint-disable-next-line
      if (value == '') {
        return input.focus()
      }
      // eslint-disable-next-line
      if (value == row._value) {
        row._editing = false
        return
      }
      row.value = value
      const params = {
        tagCode: row.tagCode,
        id: row.id,
        xval: row.value,
        source: '1',
        cycle: this.period
      }
      return api.updateRealTimeData(params).then(res => {
        if (res.code === 200) {
          row._editing = false
        }
      }).finally(() => {
        this.reload()
      })
    },
  },
}
</script>

<style scoped>

</style>
